/*
     Copyright 2007 Joseph M. Ferner

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

namespace OpenServers.Net.Common.FileSystem {
    /// <summary>
    /// collection of methods for working with the file system.
    /// </summary>
    public class FileSystemUtils {
        /// <summary>
        /// gets a object given a directory and path. this is really a helper function for directories to implement GetObject.
        /// </summary>
        public static IFileSystemObject GetObject(IDirectory directory, string path) {
            if (path.StartsWith("/")) {
                path = path.Substring(1);
            }
            if (path.Length == 0) {
                return directory;
            }
            int firstPathToken = path.IndexOf('/');
            string firstPath;
            string restOfPath = null;
            if (firstPathToken > 0) {
                firstPath = path.Substring(0, firstPathToken);
                restOfPath = path.Substring(firstPathToken + 1);
            } else {
                firstPath = path;
            }

            foreach (IFileSystemObject item in directory.GetItems()) {
                if (item.Name == firstPath) {
                    if (restOfPath == null) {
                        return item;
                    } else if (item is IDirectory) {
                        return ((IDirectory)item).GetObject(restOfPath);
                    }
                }
            }

            if (restOfPath == null) {
                return directory.CreateFile(firstPath);
            } else {
                IDirectory dir = directory.CreateDirectory(firstPath);
                if (restOfPath.Length > 0) {
                    return dir.GetObject(restOfPath);
                } else {
                    return dir;
                }
            }
        }

        /// <summary>
        /// Get the full path of a file system object.
        /// </summary>
        public static string GetFullPath(IFileSystemObject fso) {
            if (fso.Parent != null) {
                return fso.Parent.FullPath + fso.Name + (fso is IDirectory ? "/" : "");
            } else {
                return fso.Name;
            }
        }
    }
}
